<script setup>
import { uniqueFunc } from '@/utils/common.js';
import {getPageProducts} from '@/api/ShopDatabase/index.js';
import { queryCoupons } from '@/api/Marketing/coupon.js';
import { limitInt } from '@/utils/common.js';
const emits = defineEmits(["backCoupon"])
const formInline = ref([

])
const btnLefts = ref([]);
const btnRights = ref([])

const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const sendType = ref(0);
const couponFlag = ref(false);
const checkData = ref([]);
const seachTable = ref(null);
const selectHandle = (val,row)=>{
    let index = checkData.value.map(value=>value.id).indexOf(row.id);
    if(index >=0){
        removeData([row.id]);
    }else{
        checkData.value = uniqueFunc([row,...checkData.value],'id');
    }
}
const selectAllChange = (col)=>{
    if(col.length>0){
        checkData.value = uniqueFunc([...col,...checkData.value],'id');
    }else{
        let ids = tableData.value.map(value=>value.id);
        removeData(ids);
    }
}
//移除未选中的数据
const removeData = (ids)=>{
    checkData.value = checkData.value.filter(value=>ids.indexOf(value.id) == -1);
};
const toggleSelection = ()=>{
  //获取所有选中的id
  let ids = [];
  ids = checkData.value.map(value=>value.id);
  //过滤获取相同值
  let repeatValue = tableData.value.filter(value=>ids.indexOf(value.id) != -1);
  seachTable.value.checkHaveData(repeatValue);
};
const tableConfig = ref([
    {
        prop: "couponsName",
        label: "优惠券名称"
    },
    {
        type: 'slot',
        label: '赠券数',
        prop: 'sendNum',
        width: 150,
        needHeader: true,
        slotHeaderName: 'sendNumHeader',
        slotName: 'sendNum'
    },
    {
        prop: "maxNum",
        label: "剩余数量",
        width:80
    },
    {
      prop: "offerContent",
      label: "优惠内容",
      type:"slot",
      slotName:'offerContent',
      width:220
    },
    {
        prop: "couponsRemark",
        label: "备注名称",
        width:70
    },
    {
      prop: "useTime",
      label: "使用时间",
      width:200,
      format:(value,row)=>{
        if(row.usingType == 0){
          return [row.usingStartTime,row.usingEndTime].join("~")
        }else if(row.usingType == 1){
          return `领取后${ row.usingDay || 0 }天内有效`
        }
      }
    },
])
const handlerSearch = async (formInline)=>{
    
    tableLoading.value = true;
    try{
        let params = {
            ...formInline,
            filterZero:true,
            couponsStatus:0
        }
        let result = await queryCoupons(params);
        totalPage.value = Number(result.total);
        
        tableData.value = result.records.map(value=>{
            let sendNum;
            let diffNum = Number(value.releaseTotalNum) - Number(value.releaseNum)
            checkData.value.forEach(lis=>{
                if(lis.id == value.id){
                    sendNum = lis.sendNum;
                }
            })
            return {
                ...value,
                sendNum:sendNum || 1,
                maxNum:diffNum,

            }
        })
        disabledCheckBox(checkData.value);
        nextTick(()=>{
            toggleSelection();
        })
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const changeSendNum = (index)=>{

    if((tableData.value[index].sendNum??'') === ''){
        tableData.value[index].sendNum = 1
    }
    if(tableData.value[index].sendNum<1){
        tableData.value[index].sendNum = 1;
    }
    if(sendType.value == 0){
        if(tableData.value[index].maxNum > 2){
            if(tableData.value[index].sendNum>2){
                tableData.value[index].sendNum = 2;
            }
        }else{
            if(tableData.value[index].sendNum>tableData.value[index].maxNum){
                tableData.value[index].sendNum = tableData.value[index].maxNum;
            }
        }

    }else if(sendType.value == 1){
        if(tableData.value[index].sendNum>tableData.value[index].maxNum){
            tableData.value[index].sendNum = tableData.value[index].maxNum;
        }
    }
    syncCheckData();
    
}
//同步选中数据
const syncCheckData = ()=>{
    checkData.value.forEach((lis,key)=>{
        tableData.value.forEach(value=>{
            if(lis.id == value.id){
                checkData.value[key] = value;
            }
        })
    })

}
const openModal =(sendTypeInfo = 0,checkValue = [] , type = 1)=>{
    console.log(sendTypeInfo,checkValue);
    sendType.value = sendTypeInfo;
    checkData.value = checkValue;
    nextTick(()=>{
        couponFlag.value = true;
    })

}
const confrimCoupon = ()=>{
    emits("backCoupon",checkData.value);
    couponFlag.value = false;
}
const editSendNum = (id,val,row)=>{
    row.sendNum=limitInt(row.sendNum)
    let index = checkData.value.findIndex(lis=>lis.id == id);
    if(index != -1){
        console.log(index,val,222); 
        checkData.value[index].sendNum = val;
    }

}
const allSelectFlag = computed(()=>{
    return sendType.value == 0?true:false;
});
const disabledCheckBox = (val)=>{
    if(sendType.value == 0){
        if(val.length>=3){
            let ids = val.map(value=>value.id);
            tableData.value.forEach((lis,index)=>{  
                if(!ids.includes(lis.id)){
                    tableData.value[index].selectable = false;
                }else{
                    tableData.value[index].selectable = true;
                }
                
                
            })

        }else{
            tableData.value.forEach((lis,index)=>{
                
                tableData.value[index].selectable = true;
                
            })

        }
    }
}
watch(checkData,(val)=>{
    disabledCheckBox(val);
})
defineExpose({openModal})
</script>
<template>
    <el-dialog v-model="couponFlag" title="选择优惠券" width="1000px">
        <div style="width:100%;height:500px" v-if="couponFlag">
            <SeachTable 
                :tableType="2"
                :tableSelection="true" 
                ref="seachTable"
                :forms="formInline"
                :btnLefts="btnLefts"
                :btnRights="btnRights"
                :tableLoading="tableLoading"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :totalPage="totalPage"
                @handlerSearch="handlerSearch"
                :showLine="false"
                :showBtn="false"
                @selectHandle="selectHandle"
                @selectAllHandle="selectAllChange"
                :allSelectFlag="allSelectFlag"

            >
            <template #sendNumHeader v-if="sendType == 0">
                <div class="info-show">
                    <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                        赠券数
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                                赠券数：单个发券对象发放数量
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #sendNum="{ row,index }" v-if="sendType == 0">

                <el-input size="small" placeholder="请输入" v-model="row.sendNum" style="width:100px" @blur="changeSendNum(index)" @input="val=>editSendNum(row.id,val,row)"></el-input>
            </template>
            <template #offerContent="{ row }">
                <div class="info-show">
                    <div class="text-show" >
                        满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}
                        
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                              1.优惠内容：满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}；
                              2.适用门店及业务：{{ row.businessScope  == 0?'全部门店及业务':`指定门店及业务` }}；
                              3.适用范围：{{ ["全部商品可用","指定商品可用","指定商品不可用"][row.activityScope] }}
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            </SeachTable>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="couponFlag = false">取消</el-button>
                <el-button type="primary" @click="confrimCoupon()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style lang="less" scoped>
.tips-info{
    max-width: 300px; 
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
        
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}
:deep(.el-table__row){
    .el-input .el-input__wrapper{
        background: rgba(0,0,0,0);
    }
}
:deep(.search-line){
    padding:0;
}
:deep(.search-table .table){
    padding:0;
}
.text-info{
    width: 100%;
    font-size: 14px;
    font-weight: 400;
    line-height: 14px;
    color: #222222;
}
:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3480FF;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}

:deep(.el-table__header){
    tr{
        th{
            .cell{
                border-right: 0px;
            }
        }
    }
}
</style>